import CryptoJS from 'crypto-js'

/**
 * MD5加密
 * @param data
 * @returns {*}
 */
export function md5Entry (data) {
  return CryptoJS.MD5(data)
}

/**
 * 加密
 */
export function encrypt (str) {
  // 秘钥
  var key = CryptoJS.enc.Utf8.parse('X2bJDtJtM7IAmbpB')
  // 向量iv
  var iv = CryptoJS.enc.Utf8.parse('9338010611913253')
  var encrypted = CryptoJS.AES.encrypt(str, key, {iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7})
  return encrypted.toString()
}

/**
 * 解密
 * @param str
 */
export function decrypt (str) {
  // 秘钥
  var key = CryptoJS.enc.Utf8.parse('X2bJDtJtM7IAmbpB')
  // 向量iv
  var iv = CryptoJS.enc.Utf8.parse('9338010611913253')
  var decrypted = CryptoJS.AES.decrypt(str, key, { iv: iv, padding: CryptoJS.pad.Pkcs7 })
  return decrypted.toString(CryptoJS.enc.Utf8)
}

/**
 * ES6: base64解码
 */
export function decodeBase64Content (base64Content) {
  let commonContent = base64Content.replace(/\s/g, '+')
  commonContent = Buffer.from(commonContent, 'base64').toString()
  return commonContent
}

/**
 * ES6: base64编码
 */
export function encodeBase64Content (commonContent) {
  let base64Content = Buffer.from(commonContent).toString('base64')
  return base64Content
}

/**
 * 截取url问号后面的参数
 */
export function urlParams () {
  const url = window.location.href
  var i = url.indexOf('?')
  // 获取url问号后面的参数
  var params = url.substring(i + 1, url.length)
  return params
}

/**
 * 截取url参数后面的值
 * @param para
 */
export function getUrl (k) {
  var regExp = new RegExp('([?]|&)' + k + '=([^&]*)(&|$)')
  var result = window.location.href.match(regExp)
  if (result) {
    return decodeURIComponent(result[2])
  } else {
    return null
  }
}

/**
 * 去除空格
 * @param str
 */
export function Trim (str) {
  return str.replace(/(^\s*)|(\s*$)/g, '')
}
